﻿using System;
using System.Linq;
using System.IO;
using System.Reflection;
using System.Xml.Linq;

namespace MakeSerializable
{
    public class ProjectKeyReader
    {

        public StrongNameKeyPair StrongNameKeyPair { get; set; }

        static string GetKeyFile(string projectPath)
        {
            var xDocument = XDocument.Load(projectPath);
            return (
                    from c in xDocument.BuildDescendants("AssemblyOriginatorKeyFile")
                    select c.Value)
                .FirstOrDefault();
        }

        static bool IsSignAssemblyTrue(string projectPath)
        {
            var xDocument = XDocument.Load(projectPath);
            var signAssembly = (
                                from c in xDocument.BuildDescendants("SignAssembly")
                                select c.Value)
                .FirstOrDefault();
            return string.Equals(signAssembly, "true", StringComparison.InvariantCultureIgnoreCase);
        }

        public void Execute(string projectFilePath)
        {
            var assemblyKeyFilePath = "";

            if (!IsSignAssemblyTrue(projectFilePath))
            {
                return;
            }

            var assemblyOriginatorKeyFile = GetKeyFile(projectFilePath);
            if (assemblyOriginatorKeyFile == null)
            {
                return;
            }
            assemblyKeyFilePath = Path.Combine(Path.GetDirectoryName(projectFilePath), assemblyOriginatorKeyFile);


            StrongNameKeyPair = new StrongNameKeyPair(File.OpenRead(assemblyKeyFilePath));
        }
    }
}